package Servlet;

import bean.Message;
import bean.User;
import dao.MessageDao;
import dao.UserDao;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "addPeople", value = "/addPeople")
public class addPeople extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String id = request.getParameter("id");
        String myID = request.getParameter("myID");
        System.out.println(myID);
        System.out.println(id);
        User user = new User();
        user.setId(id);
        User user1 = new User();
        user1.setId(myID);
        UserDao userDao = new UserDao();
        boolean flag = userDao.addFriend(user1,user);
        boolean flag1 = false;
        if(flag){
            MessageDao messageDao = new MessageDao();
            Message message = new Message(myID , id);
            message.setContent("你们已经是好友了，开始聊天吧");
            flag1 = messageDao.sendMessage(message);
        }
        PrintWriter out = response.getWriter();
        Map map = new HashMap();
        if(flag1){

            map.put("flag", flag);

            out.print(JSONObject.fromObject(map));
        }else{
            out.print(JSONArray.fromObject(map));
        }
      

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
